package com.cskaoyan.utils;

import com.cskaoyan.exception.TestException;
import com.cskaoyan.model.vo.BaseRespVo;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * @program: project-marker
 * @description: 数据验证工具类
 * @author: fish-team
 * @create: 2021-11-29 09:19
 **/

public class ValidatorUtil {

    public static BaseRespVo valid(BindingResult bindingResult) {

        if (!bindingResult.hasErrors()) {
            return BaseRespVo.ok("校验成功");
        }
        // 错误的参数对象
        FieldError fieldError = bindingResult.getFieldError();

        // 实际传入的被拒绝的参数值
        Object rejectedValue = fieldError.getRejectedValue();

        // 获取错误的参数名
        String field = fieldError.getField();

        // 默认信息
        String defaultMessage = fieldError.getDefaultMessage();

        String message = "请求参数" + field + "因为传入了值"
                + rejectedValue + "导致校验失败：" + defaultMessage;

        return BaseRespVo.fail(message);

    }

    // 抛出异常

    public static BaseRespVo valid2(BindingResult bindingResult) throws Exception {

        if (!bindingResult.hasErrors()) {
            return BaseRespVo.ok("校验成功");
        }
        // 错误的参数对象
        FieldError fieldError = bindingResult.getFieldError();

        // 实际传入的被拒绝的参数值
        Object rejectedValue = fieldError.getRejectedValue();

        // 获取错误的参数名
        String field = fieldError.getField();

        // 默认信息
        String defaultMessage = fieldError.getDefaultMessage();

        String message = "请求参数" + field + "因为传入了值"
                + rejectedValue + "导致校验失败：" + defaultMessage;

        throw new TestException(message);

    }


}
